package io.zhengsh.nio.files;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.Future;

public class AsynchronousFileChannelDemo {

    public static void main(String[] args) throws IOException {
        Path path = Paths.get("/Users/zhengsh/" +
                "sourcecode.io/zhengsh-vvip/nio/src/main/resources/01.txt");
        AsynchronousFileChannel fileChannel = null;
        try {

            fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
        } catch (IOException e) {
            e.printStackTrace();
        }

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        long position = 0;
        Future<Integer> future = fileChannel.read(buffer, position);

        while (!future.isDone()) {
            ;
        }

        buffer.flip();
//        while (buffer.remaining() > 0) {
//            System.out.println(buffer.get());
//        }

        byte[] data = new byte[buffer.limit()];
        buffer.get(data);
        System.out.println(new String(data));

        buffer.clear();
        fileChannel.close();
    }
}
